package com.simple.framework.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.simple.common.core.domain.model.LoginUser;
import com.simple.common.utils.ServletUtils;
import com.simple.framework.web.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * mybatis-plus自动注入配置
 *
 * @author SimpleZzz
 * @date 2020/12/01 14:47:26
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Autowired
    TokenService tokenService;
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "createBy", String.class, loginUser.getUsername());
        this.strictInsertFill(metaObject, "updateBy", String.class, loginUser.getUsername());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        this.strictUpdateFill(metaObject, "updateBy", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateBy", String.class, loginUser.getUsername());
    }
}
